﻿using System;
using CoreTypes;
using System.Linq;
using System.Custom;
using CustomControls;
using System.Drawing;
using System.Custom.Window;
using System.Globalization;
using System.Windows.Forms;
using System.ComponentModel;
using MainModule.Properties;

namespace MainModule
{
   public partial class AddContactWindow : Window
   {
      #region Window Data

      User FUser;
      bool FAskToSave;
      Account FAccount;
      InternetCommunicator FCommunicator = InternetCommunicator.Self;

      User User
      {
         get
         {
            if (FUser == null) FUser = new User(textBoxUsername.Text);

            return FUser;
         }
      }

      #endregion

      public AddContactWindow()
      {
         InitializeComponent();

         FCommunicator.PropertyChanged += communicator_PropertyChanged;
         FCommunicator.ContactsChanged += communicator_ContactsChanged;
         FCommunicator.RequestUserInfoState += communicator_RequestUserInfoState;

         IItemView view = itemViewGroups.AddItemView("Groups", "Groups", "", ViewStyle.Tree);
         view.XmlAssign += new EventHandler<ItemViewXmlAssignEventArgs>(itemViewEntry_XmlAssign);
         view.ShowSplitters = false;
         view.AllowDrag = false;

         buttonAddGroup.Tag = buttonAddGroup.Top;
         buttonAddGroup.Top = itemViewGroups.Top;

         ColorTheme = FCommunicator.ColorTheme;

         Icon = Icon.FromHandle(Resources.New16.GetHicon());
      }
      protected override void Dispose(bool disposing)
      {
         FCommunicator.PropertyChanged -= communicator_PropertyChanged;
         FCommunicator.ContactsChanged -= communicator_ContactsChanged;
         FCommunicator.RequestUserInfoState -= communicator_RequestUserInfoState;
         
         if (disposing && (components != null))
         {
            components.Dispose();
         }
         base.Dispose(disposing);
      }

      public override ColorTheme ColorTheme
      {
         get
         {
            return base.ColorTheme;
         }
         set
         {
            base.ColorTheme = value;
            Refresh();
         }
      }

      public void Show(User user, bool askToSave)
      {
         FUser = user;
         FAskToSave = askToSave;
         FAccount = FCommunicator.CurrentAccount;
         
         textBoxMessage.Text = "";
         textBoxUsername.Text = "";
         textBoxGroupName.Text = "";
         comboBoxCustomName.Text = "";
         tabControl.SelectedIndex = 0;
         comboBoxCustomName.Items.Clear();
         buttonAddGroup.Top = itemViewGroups.Top;
         labelGroupName.Visible = textBoxGroupName.Visible = false;
         labelUsername.Text = FCommunicator.CurrentAccount.ServiceConfig.Service.LoginAlias + ":";

         comboBoxAccounts.Items.Clear();
         foreach (Account account in FCommunicator.ActiveAccounts.Where(a =>
            a.ServiceConfig.Service.ProtocolName == FCommunicator.CurrentAccount.ServiceConfig.Service.ProtocolName))
         {
            comboBoxAccounts.Items.Add(account);
         }
         comboBoxAccounts.SelectedItem = FCommunicator.CurrentAccount;

         if (FUser == null)
         {
            labelUsername.Enabled = true;
            textBoxUsername.ReadOnly = false;
            textBoxUsername.Select();
         }
         else
         {
            labelUsername.Enabled = false;
            textBoxUsername.ReadOnly = true;
            textBoxUsername.Text = FUser.Login;
            
            UpdateCustomName();

            comboBoxCustomName.Select();
         }

         Visualize();
      }
      public override void Translate(CultureInfo culture)
      {
         base.Translate(culture);
         UpdatewWindowView();
      }

      private void RequestUserInfo()
      {
         if (FAccount != null && textBoxUsername.Text != "")
         {
            //CoreTypes.EventLog.AddRecord("RequestUserInfo", true);
            FAccount.ServiceDriver.RequestUserInfo(User, true);
         }
      }
      private void UpdateCustomName()
      {
         if (FAccount != null && FUser != null)
         {
            comboBoxCustomName.Items.Clear();
            comboBoxCustomName.Text = FUser.Nickname;
            long a = 0; string s;
            if (FUser.Nickname != FUser.Identifier) comboBoxCustomName.Items.Add(FUser.Nickname);
            if (!long.TryParse(FUser.Login, out a) && !comboBoxCustomName.Items.Contains(FUser.Login)) comboBoxCustomName.Items.Add(FUser.Login);
            if (FUser.Login.Contains('@') && !comboBoxCustomName.Items.Contains(s = FUser.Login.SubstrBefore("@"))) comboBoxCustomName.Items.Add(s);
            if (FUser.Info.FullName != "" && !comboBoxCustomName.Items.Contains(FUser.Info.FullName.TrimIgnoreNull())) comboBoxCustomName.Items.Add(FUser.Info.FullName);
         }
      }
      protected override void UpdatewWindowView()
      {
         labelUsername.Text = FCommunicator.CurrentAccount.ServiceConfig.Service.LoginAlias + ":";
      }

      private void labelInfo_Click(object sender, EventArgs e)
      {
         if (textBoxUsername.Text == "")
         {
            MessageBox.Show(Resources.S_Enter_LoginCaption_of_the_user.Replace("<LoginCaption>",
               FCommunicator.CurrentAccount.ServiceConfig.Service.LoginAlias), Text, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            tabControl.SelectedTab = tabPageGeneral;
            textBoxUsername.Select();
            return;
         }

         FCommunicator.ShowUserProperties(User, null);
      }
      private void window_KeyDown(object sender, KeyEventArgs e)
      {
         if (e.KeyCode == Keys.Enter)
         {
            if (textBoxUsername.Text == "")
            {
               tabControl.SelectedTab = tabPageGeneral;
               textBoxUsername.Select();
            }
            else if (textBoxUsername.Focused && comboBoxCustomName.Text == "")
            {
               tabControl.SelectedTab = tabPageGeneral;
               comboBoxCustomName.Select();
            }
            else
            {
               buttonAddContact_Click(sender, EventArgs.Empty);
            }
         }
      }
      private void buttonCancel_Click(object sender, EventArgs e)
      {
         Close();
      }
      private void tabPage_Paint(object sender, PaintEventArgs e)
      {
         //InternetCommunicator.Self.DrawTheme(InternetCommunicator.Self.ColorTheme, e.Graphics, (sender as Control).ClientRectangle, ColorThemeObject.ToolStrip);
      }
      private void buttonAddGroup_Click(object sender, EventArgs e)
      {
         if (buttonAddGroup.Top != (int)buttonAddGroup.Tag)
         {
            labelGroupName.Visible = true;
            textBoxGroupName.Visible = true;
            buttonAddGroup.Top = (int)buttonAddGroup.Tag;
         }
         if (textBoxGroupName.Text == "")
         {
            textBoxGroupName.Focus();
            return;
         }
         DataItem selected = itemViewGroups["Groups"].SelectedItem;
         FCommunicator.AddContactGroup(textBoxGroupName.Text, selected != null ? selected.Name : "", (Account)comboBoxAccounts.SelectedItem);
         textBoxGroupName.Text = "";
      }
      private void panelBase_Paint(object sender, PaintEventArgs e)
      {
         FCommunicator.DrawTheme(ColorTheme, e.Graphics, (sender as Control).ClientRectangle, ColorThemeObject.Window);
      }
      private void textBoxUsername_Leave(object sender, EventArgs e)
      {
         if (comboBoxCustomName.Items.Count == 0) RequestUserInfo();
      }
      private void panelBottom_Paint(object sender, PaintEventArgs e)
      {
         FCommunicator.DrawTheme(ColorTheme, e.Graphics, (sender as Control).ClientRectangle, ColorThemeObject.PanelV);
      }
      private void buttonAddContact_Click(object sender, EventArgs e)
      {
         if (textBoxUsername.Text == "")
         {
            MessageBox.Show(Resources.S_Enter_LoginCaption_of_the_user.Replace("<LoginCaption>",
               FCommunicator.CurrentAccount.ServiceConfig.Service.LoginAlias), Text, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            tabControl.SelectedTab = tabPageGeneral;
            textBoxUsername.Select();
            return;
         }

         DataItem selected = itemViewGroups["Groups"].SelectedItem;

         FCommunicator.AddContact((Account)comboBoxAccounts.SelectedItem, User,
                                  selected != null ? selected[typeof(ContactGroup)] as ContactGroup : null,                                  
                                  true, textBoxMessage.Text);
         Close();
      }
      private void panelUserBody_Paint(object sender, PaintEventArgs e)
      {
         FCommunicator.DrawTheme(ColorTheme, e.Graphics, (sender as Control).ClientRectangle, ColorThemeObject.Pattern);
         //FCommunicator.DrawTheme(ColorTheme, e.Graphics, (sender as Control).ClientRectangle, ColorThemeObject.Area);
      }
      private void panelUserHeader_Paint(object sender, PaintEventArgs e)
      {
         FCommunicator.DrawTheme(ColorTheme.Standard, e.Graphics, (sender as Control).ClientRectangle, ColorThemeObject.Pattern);
      }
      private void linkLabelSelectGroup_Click(object sender, EventArgs e)
      {
         tabControl.SelectedIndex = 1;
      }
      private void window_FormClosed(object sender, FormClosedEventArgs e)
      {
         FUser = null;
      }
      private void textBoxUsername_TextChanged(object sender, EventArgs e)
      {
         if (textBoxUsername.Text != "" && !textBoxUsername.ReadOnly)
         {
            FUser = null;
            comboBoxCustomName.Text = "";
            comboBoxCustomName.Items.Clear();
         }
      }
      private void comboBoxCustomName_TextUpdate(object sender, EventArgs e)
      {
         if (FUser != null) FUser.CustomName = comboBoxCustomName.Text;
      }
      private void comboBoxAccounts_SelectedIndexChanged(object sender, EventArgs e)
      {
         Account account = (Account)comboBoxAccounts.SelectedItem;
         ItemView view = itemViewGroups["Groups"];
         view.SetXStructure(account.XContacts, this);
         view.SelectedItem = view[account.DefaultGroup.Name];
         if (view.SelectedItem == null && view.Items.Count > 0) view.SelectedItem = view.Items[0];
         buttonAddGroup.Enabled = FCommunicator.CurrentAccount.ServiceConfig.SupportsFeature(ServiceFeatures.AddGroup);
      }
      private void itemViewEntry_XmlAssign(object sender, ItemViewXmlAssignEventArgs e)
      {
         e.SkipItem = !e.IsGroup;
      }
      private void communicator_PropertyChanged(object sender, PropertyChangedEventArgs e)
      {
         if (e.PropertyName == "ColorTheme") ColorTheme = FCommunicator.ColorTheme;
         else if (e.PropertyName == "Culture") Translate(FCommunicator.Culture);
      }
      private void communicator_ContactsChanged(object sender, ContactsChangedEventArgs e)
      {
         comboBoxAccounts_SelectedIndexChanged(sender, null);
      }
      private void communicator_RequestUserInfoState(object sender, NetworkOperationEventArgs e)
      {
         User user = (User)e.GetResult("User", null);

         //CoreTypes.EventLog.AddRecord("RequestUserInfo " + user == null ? "" : user.ToDisplayString(), true);

         if (user != FUser) return;

         if (e.State == OperationState.Completed) UpdateCustomName();
      }
   }
}